package com.example.ying.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.ying.common.R;
import com.example.ying.common.utils.RedisKeyUtil;
import com.example.ying.common.utils.RedisUtil;
import com.example.ying.mapper.CommentMapper;
import com.example.ying.model.domain.Comment;
import com.example.ying.model.request.CommentLikedRequest;
import com.example.ying.model.request.CommentRequest;
import com.example.ying.service.CommentService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class CommentServiceImpl extends ServiceImpl<CommentMapper, Comment> implements CommentService {
    @Autowired
    private CommentMapper commentMapper;
    @Autowired
    private RedisUtil redisUtil;

    @Override
    public R addComment(CommentRequest addCommentRequest) {
        Comment comment = new Comment();
        BeanUtils.copyProperties(addCommentRequest, comment);
        if (commentMapper.insert(comment) > 0) {
            return R.success("评论成功");
        } else {
            return R.error("评论失败");
        }
    }

    @Override
    public R updateCommentLiked(CommentLikedRequest commentLikedRequest) {
        String hkey = RedisKeyUtil.getLikedKey(commentLikedRequest.getLikedCommentId(),commentLikedRequest.getLikedUserId());
        if(redisUtil.hasHashKey(RedisKeyUtil.MAP_KEY_COMMENT_LIKED_DETAIL,hkey)&&redisUtil.getCacheHash(RedisKeyUtil.MAP_KEY_COMMENT_LIKED_DETAIL,hkey).equals(commentLikedRequest.getStatus())){
            return R.warning("重复请求！");
        }
        //缓存表：用户点赞状态
        redisUtil.setCacheHash(RedisKeyUtil.MAP_KEY_COMMENT_LIKED_DETAIL,hkey,commentLikedRequest.getStatus());
        //缓存表：点赞总数
        if(commentLikedRequest.getStatus()==0){
            redisUtil.incrementCacheHash(RedisKeyUtil.MAP_KEY_COMMENT_LIKED_COUNT,commentLikedRequest.getLikedCommentId(),-1);
        }else{
            redisUtil.incrementCacheHash(RedisKeyUtil.MAP_KEY_COMMENT_LIKED_COUNT,commentLikedRequest.getLikedCommentId(),1);
        }
        return R.success("点赞成功");
    }

    //    删除评论
    @Override
    public R deleteComment(Integer id) {
        if (commentMapper.deleteById(id) > 0) {
            return R.success("删除成功");
        } else {
            return R.error("删除失败");
        }
    }

    @Override
    public R getCommentsBymovieId(Integer movieId) {
         return R.success(null,commentMapper.selectByMovieId(movieId));
    }
}
